<template>
  <div class="chat-container" :class="`theme-${currentTheme}`">
    <particle-background :theme="currentTheme" :particle-count="40" />
    
    <div class="chat-header">
      <router-link to="/" class="back-btn">
        <span>&larr;</span> 返回
      </router-link>
      <h1>AI 编程大师</h1>
      <button class="theme-toggle" @click="showThemeSelector = !showThemeSelector">
        <span class="theme-icon">🎨</span>
      </button>
      <div class="session-id">会话ID: {{ chatId }}</div>
    </div>
    
    <div class="theme-selector" v-if="showThemeSelector">
      <theme-switcher 
        :themes="availableThemes" 
        :active-theme="currentTheme" 
        @change-theme="changeTheme"
      />
    </div>
    
    <div class="messages-container" ref="messagesContainer">
      <div v-if="messages.length === 0" class="welcome-message">
        <h3>欢迎使用AI编程大师</h3>
        <p>您的专属代码顾问已准备就绪，可以解答您关于编程、技术方面的问题。</p>
        <div class="suggestion-list">
          <div class="suggestion-title">您可以尝试询问：</div>
          <div class="suggestion-item" @click="useExample('如何用Python实现二分查找算法？')">如何用Python实现二分查找算法？</div>
          <div class="suggestion-item" @click="useExample('React中如何管理复杂的状态？')">React中如何管理复杂的状态？</div>
          <div class="suggestion-item" @click="useExample('请编写一个简单的网页爬虫代码')">请编写一个简单的网页爬虫代码</div>
        </div>
      </div>
      
      <chat-message
        v-for="(message, index) in messages"
        :key="index"
        :content="message.content"
        :is-user="message.isUser"
        :timestamp="message.timestamp || Date.now()"
        avatar-type="codemaster"
      />
    </div>
    
    <chat-input 
      :is-loading="loading" 
      @send="sendMessage"
    />
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'
import ChatMessage from '../components/ChatMessage.vue'
import ChatInput from '../components/ChatInput.vue'
import ParticleBackground from '../components/ParticleBackground.vue'
import ThemeSwitcher from '../components/ThemeSwitcher.vue'
import { createCodeMasterChat } from '../api'

export default {
  name: 'CodeMasterView',
  components: {
    ChatMessage,
    ChatInput,
    ParticleBackground,
    ThemeSwitcher
  },
  data() {
    return {
      chatId: '',
      messages: [],
      loading: false,
      eventSource: null,
      currentTheme: 'blue',
      showThemeSelector: false,
      requestInProgress: false,
      maxRetryAttempts: 3,
      retryAttempts: 0,
      backendDown: false,
      availableThemes: [
        {
          id: 'blue',
          name: '深蓝代码',
          colors: {
            primary: '#2196f3',
            secondary: '#1565c0'
          }
        },
        {
          id: 'dark',
          name: '暗黑模式',
          colors: {
            primary: '#424242',
            secondary: '#212121'
          }
        },
        {
          id: 'green',
          name: '翠绿终端',
          colors: {
            primary: '#4caf50',
            secondary: '#2e7d32'
          }
        },
        {
          id: 'purple',
          name: '紫色科技',
          colors: {
            primary: '#9c27b0',
            secondary: '#6a1b9a'
          }
        }
      ],
      reconnectionDelay: 2000,
      keepConnection: true,
      lastMessage: '',
    }
  },
  created() {
    // 尝试从localStorage加载主题设置
    const savedTheme = localStorage.getItem('codeMasterTheme');
    if (savedTheme && this.availableThemes.some(theme => theme.id === savedTheme)) {
      this.currentTheme = savedTheme;
    }
    
    // 生成一个唯一的聊天室ID
    this.chatId = uuidv4()
    
    // 添加一条欢迎消息
    this.messages.push({
      content: '你好！我是AI编程大师，有什么关于编程技术方面的问题可以问我。',
      isUser: false
    })

    // 设置页面标题
    document.title = 'AI编程大师 - 专业的编程辅助服务';
    
    // 检查URL查询参数是否包含问题，如果有则自动发送
    const queryQuestion = this.$route.query.q;
    if (queryQuestion) {
      // 使用setTimeout确保组件完全挂载后再发送消息
      setTimeout(() => {
        this.sendMessage(queryQuestion);
      }, 1000);
    }
  },
  head: {
    title: 'AI编程大师 - 专业的编程辅助服务',
    meta: [
      { name: 'description', content: 'AI编程大师为您提供专业的编程技术支持，解答开发问题，生成代码示例，帮助您解决技术难题。' },
      { name: 'keywords', content: 'AI编程大师,编程助手,代码生成,技术顾问,AI开发支持' }
    ]
  },
  methods: {
    sendMessage(message) {
      console.log('发送消息:', message)
      
      // 如果已经有一个请求正在进行中，则忽略新的请求
      if (this.requestInProgress) {
        console.log('请求正在处理中，忽略新请求')
        return
      }
      
      // 设置请求处理中状态
      this.requestInProgress = true
      
      // 重置重试状态和后端状态标志
      this.retryAttempts = 0;
      this.backendDown = false;
      
      // 添加用户消息到聊天记录
      this.messages.push({
        content: message,
        isUser: true,
        timestamp: Date.now()
      })
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      this.loading = true
      
      // 关闭之前的连接（如果有）
      if (this.eventSource) {
        this.eventSource.close()
      }
      
      // 创建新的SSE连接
      this.eventSource = createCodeMasterChat(message, this.chatId)
      
      // 创建一个新的AI消息占位
      const aiMessageIndex = this.messages.length
      this.messages.push({
        content: '',
        isUser: false,
        timestamp: Date.now()
      })
      
      // 处理返回的消息流
      this.eventSource.onmessage = (event) => {
        try {
          const response = event.data
          if (response) {
            // 更新AI消息内容
            this.messages[aiMessageIndex].content += response
            
            // 检查用户是否在底部，仅当用户在底部时自动滚动
            this.$nextTick(() => {
              const container = this.$refs.messagesContainer
              if (container) {
                // 检查是否在底部或接近底部
                const isAtBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100
                if (isAtBottom) {
                  this.scrollToBottom()
                }
              }
            })
          }
        } catch (error) {
          console.error('处理SSE消息错误:', error)
        }
      }
      
      // 处理连接建立事件
      this.eventSource.onopen = () => {
        console.log('SSE连接已建立')
      }
      
      // 处理错误事件
      this.eventSource.onerror = (event) => {
        console.error('SSE连接错误:', event)
        
        // 关闭连接
        if (this.eventSource) {
          this.eventSource.close()
          this.eventSource = null
        }
        
        this.loading = false
        this.requestInProgress = false
      }
      
      // 处理连接关闭事件
      const onComplete = () => {
        this.loading = false
        this.requestInProgress = false
        
        if (this.eventSource) {
          this.eventSource.close()
          this.eventSource = null
        }
        
        console.log('SSE连接已完成')
      }
      
      // 设置超时，避免连接无限挂起
      setTimeout(() => {
        if (this.loading) {
          onComplete()
          
          // 如果消息内容为空，则显示错误信息
          if (!this.messages[aiMessageIndex].content) {
            this.messages[aiMessageIndex].content = '抱歉，服务器响应超时，请稍后再试。'
          }
        }
      }, 60000)  // 60秒超时
    },
    
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    
    useExample(example) {
      // 使用示例问题
      this.sendMessage(example)
    },
    
    changeTheme(theme) {
      this.currentTheme = theme;
      localStorage.setItem('codeMasterTheme', theme);
      this.showThemeSelector = false;
    }
  },
  beforeUnmount() {
    // 组件卸载前关闭SSE连接
    if (this.eventSource) {
      this.eventSource.close()
      this.eventSource = null
    }
    
    // 清除所有定时器
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  background-color: var(--bg-color, #121212);
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.chat-container.theme-blue {
  --primary-color: #2196f3;
  --secondary-color: #1565c0;
  --bg-color: #0a1929;
  --bubble-user-bg: #1565c0;
  --bubble-ai-bg: rgba(0, 0, 0, 0.3);
  --text-color: #ffffff;
}

.chat-container.theme-dark {
  --primary-color: #424242;
  --secondary-color: #212121;
  --bg-color: #121212;
  --bubble-user-bg: #424242;
  --bubble-ai-bg: rgba(80, 80, 80, 0.3);
  --text-color: #e0e0e0;
}

.chat-container.theme-green {
  --primary-color: #4caf50;
  --secondary-color: #2e7d32;
  --bg-color: #0d2818;
  --bubble-user-bg: #2e7d32;
  --bubble-ai-bg: rgba(0, 0, 0, 0.3);
  --text-color: #ffffff;
}

.chat-container.theme-purple {
  --primary-color: #9c27b0;
  --secondary-color: #6a1b9a;
  --bg-color: #2d1b54;
  --bubble-user-bg: #6a1b9a;
  --bubble-ai-bg: rgba(0, 0, 0, 0.3);
  --text-color: #ffffff;
}

.chat-header {
  padding: 15px 20px;
  background-color: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.chat-header h1 {
  margin: 0;
  font-size: 1.3rem;
  text-align: center;
  flex-grow: 1;
  color: var(--text-color, #ffffff);
}

.back-btn {
  display: flex;
  align-items: center;
  color: var(--text-color, #ffffff);
  text-decoration: none;
  font-size: 0.95rem;
  font-weight: 500;
  transition: opacity 0.2s;
}

.back-btn:hover {
  opacity: 0.8;
}

.back-btn span {
  margin-right: 5px;
  font-size: 1.2rem;
}

.theme-toggle {
  background: none;
  border: none;
  color: var(--text-color, #ffffff);
  font-size: 1.2rem;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 5px;
  border-radius: 5px;
  transition: background-color 0.2s;
}

.theme-toggle:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.theme-selector {
  position: absolute;
  right: 20px;
  top: 60px;
  z-index: 100;
  animation: fadeIn 0.2s;
}

.session-id {
  font-size: 0.75rem;
  color: rgba(255, 255, 255, 0.5);
  position: absolute;
  right: 70px;
  top: 50%;
  transform: translateY(-50%);
}

.messages-container {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
  position: relative;
  z-index: 1;
  color: var(--text-color);
  max-width: 1000px;
  margin: 0 auto;
  width: 100%;
  /* 调整滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: var(--primary-color) transparent;
}

.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background-color: var(--primary-color);
  opacity: 0.5;
  border-radius: 3px;
}

/* 使代码块表现良好的额外样式 */
:deep(.code-block) pre {
  margin: 0;
  white-space: pre-wrap;
}

:deep(.code-block) code {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}

.welcome-message {
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
  padding: 30px;
  border-radius: 12px;
  margin: 60px auto;
  max-width: 500px;
  animation: fadeIn 0.6s;
  border: 1px solid rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
}

.welcome-message h3 {
  margin-top: 0;
  color: var(--primary-color, #2196f3);
  font-size: 1.5rem;
}

.welcome-message p {
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.6;
}

.suggestion-list {
  margin-top: 20px;
}

.suggestion-title {
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 10px;
  font-size: 0.9rem;
}

.suggestion-item {
  background: rgba(255, 255, 255, 0.1);
  padding: 12px 15px;
  margin-bottom: 10px;
  border-radius: 8px;
  text-align: left;
  cursor: pointer;
  transition: all 0.2s;
  color: var(--text-color, #ffffff);
}

.suggestion-item:hover {
  background: var(--primary-color, #2196f3);
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@media (max-width: 768px) {
  .chat-header h1 {
    font-size: 1.1rem;
  }
  
  .session-id {
    display: none;
  }
  
  .welcome-message {
    padding: 20px;
    margin: 20px auto;
  }
}
</style> 